package com.sky.service.admin.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.anno.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.constant.RedisConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.enumeration.OperationType;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.DishNameExistException;
import com.sky.mapper.admin.DishFlavorMapper;
import com.sky.mapper.admin.DishMapper;
import com.sky.mapper.admin.SetmealDishMapper;
import com.sky.mapper.common.CategoryMapper;
import com.sky.pojo.Category;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.admin.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Author:篍
 * @Date: 2025/08/15 22:58
 * @Description: 菜品服务实现类
 */
@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Resource
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @AutoFill(OperationType.INSERT)
    public void add(DishDTO dishDTO) {
        String dishName = dishDTO.getName();
        Long count=dishMapper.countName(dishName);
        if (count>0){
            throw new DishNameExistException("菜品已存在");
        }
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);
        Long dishId = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (CollectionUtil.isNotEmpty(flavors)) {
            flavors.forEach(flavor -> {
                flavor.setDishId(dishId);
            });
            dishFlavorMapper.insertBatch(flavors);
        }
        try {
            // 删除所有以index_dish_cache:开头的缓存
            Set<String> keys = redisTemplate.keys(RedisConstant.INDEX_DISH_CACHE_PREFIX + "*");
            if (keys != null && !keys.isEmpty()) {
                redisTemplate.delete(keys);
            }
        }catch (Exception e){
            log.error("删除缓存失败{}", e.getMessage());
        }
    }

    /**
     * 菜品启售/停售
     *
     * @param id
     * @param status
     */
    @Override
    @Transactional
    public void updateStatus(Long id, Integer status) {
        Long updateUser= BaseContext.getCurrentId();
        LocalDateTime now = LocalDateTime.now();
        dishMapper.updateStatus(id, status,now, updateUser);
        try {
            // 删除所有以index_dish_cache:开头的缓存
            Set<String> keys = redisTemplate.keys(RedisConstant.INDEX_DISH_CACHE_PREFIX + "*");
            if (keys != null && !keys.isEmpty()) {
                redisTemplate.delete(keys);
            }
        }catch (Exception e){
            log.error("删除缓存失败{}", e.getMessage());
        }
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        Dish dish = dishMapper.getById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        List<DishFlavor> dishFlavor=dishFlavorMapper.getByDishId(id);
        dishVO.setFlavors(dishFlavor);
        return dishVO;
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    @AutoFill(OperationType.UPDATE)
    public void update(DishDTO dishDTO) {
        // 一.校验参数
        String dishName = dishDTO.getName();
        Long count=dishMapper.countName(dishName);
        if (count>0){
            throw new DishNameExistException("菜品已存在");
        }
        // 二.处理业务
        // 1.修改菜品基本数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);
        // 2.修改菜品品味数据
        // 2.1 删除关联数据
        dishFlavorMapper.deleteByDishId(dish.getId());
        // 2.2 增加关联数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (CollectionUtil.isNotEmpty(flavors)) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }
        try {
            // 删除所有以index_dish_cache:开头的缓存
            Set<String> keys = redisTemplate.keys(RedisConstant.INDEX_DISH_CACHE_PREFIX + "*");
            if (keys != null && !keys.isEmpty()) {
                redisTemplate.delete(keys);
            }
        }catch (Exception e){
            log.error("删除缓存失败{}", e.getMessage());
        }
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> getDishListByCategoryId(Long categoryId,String name) {
        return dishMapper.getDishListByCategoryId(categoryId,name);
    }

    /**
     * 批量删除菜品
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(List<Long> ids) {
        //查询删除的菜品是否有在起售中的
        Integer count = dishMapper.selectCountByIdsAndStatus(ids, StatusConstant.ENABLE);
        if(count>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //查询删除的菜品是否有被套餐关联的
        Integer count2= setmealDishMapper.selectCountByDishIds(ids);
        if(count2>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByDishIds(ids);
        try {
            // 删除所有以index_dish_cache:开头的缓存
            Set<String> keys = redisTemplate.keys(RedisConstant.INDEX_DISH_CACHE_PREFIX + "*");
            if (keys != null && !keys.isEmpty()) {
                redisTemplate.delete(keys);
            }
        }catch (Exception e){
            log.error("删除缓存失败{}", e.getMessage());
        }
    }
}
